﻿using SmartMotion.Core;
using Sunny.UI;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;

namespace Station
{
    public partial class FrmActionItem : UIPage
    {
        private readonly ActionItem _actionItem;
        private BindingList<MethodParms> _bindingList;
        private ConcurrentDictionary<string, VarInfo> _vars;
        private StationBase _station;

        private int[] _axis;

        private double[] _targetPosition;

        private double _speed;

        private bool _relMove;

        private bool _interpolation;

        private int _overTime;

        // public override void MovePoint(int[] axis, double[] targetPosition, double speed, bool relMove = false, bool interpolation = false,
        //int overTime = 10000)
        //
        public FrmActionItem(ActionItem actionItem)
        {
            _actionItem = actionItem;
            InitializeComponent();
            this.Load += FrmActionItem_Load;
            _axis = (int[])_actionItem.Parms[0].Value;
            _targetPosition = (double[])_actionItem.Parms[1].Value;
            if (_actionItem.Parms[2].Value == null)
            {
                _speed = 0.01;
            }
            else
            {
                _speed = (double)_actionItem.Parms[2].Value;
            }

            if (_actionItem.Parms[3].Value == null)
            {
                _relMove = false;
            }
            else
            {
                _relMove = (bool)_actionItem.Parms[3].Value;
            }

            if (_actionItem.Parms[4].Value == null)
            {
                _interpolation = false;
            }
            else
            {
                _interpolation = (bool)_actionItem.Parms[4].Value;
            }

            if (_actionItem.Parms[5].Value == null)
            {
                _overTime = 10000;
            }
            else
            {
                _overTime = Convert.ToInt32(_actionItem.Parms[5].Value);
            }
        }

        private void FrmActionItem_Load(object sender, EventArgs e)
        {
            #region 初始化表格

            if (!string.IsNullOrEmpty(_actionItem.ObjGuid))
            {
                //var v = GlobalVars.Ins.GetVar(_actionItem.ObjGuid).Value;
                try
                {
                    _station = GlobalVars.Ins.GetVar(_actionItem.ObjGuid).Value;
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                  
                }
                
            }

            SetGrid();
            _vars = GlobalVars.Ins.Vars[GlobalVars.FlowVars];
            RefreshGridData();

            #endregion 初始化表格

            #region 初始化底部控件

            cmbObj.Enabled = !_actionItem.IsStatic;
            cmbReturn.Enabled = !_actionItem.ReturnType.Contains("Void");
            cmbObj.Visible = !_actionItem.IsStatic;
            lblObj.Visible = !_actionItem.IsStatic;
            bool showRet = !_actionItem.ReturnType.Contains("Void");
            lblReturn.Visible = showRet;
            cmbReturn.Visible = showRet;
            GlobalVars.Ins.ComboTreeLoadData(cmbObj, new List<string>() { _actionItem.TypeName });
            GlobalVars.Ins.ComboTreeLoadData(cmbReturn, _actionItem.ReturnType);
            cmbObj.Text = !string.IsNullOrEmpty(_actionItem.ObjName) ? _actionItem.ObjName : "";
            cmbReturn.Text = !string.IsNullOrEmpty(_actionItem.ReturnObjName) ? _actionItem.ReturnObjName : "";
            ckbAxises.ColumnCount = 6;

            ckbAxises.Items.Clear();
            var axisEnabled = _actionItem.Parms[0];
            int[] selectedIndex = (int[])axisEnabled.Value;

            if (_station != null)
            {
                foreach (var ax in _station.Axises)
                {
                    ckbAxises.Items.Add(ax.AxisName);
                }

                if (selectedIndex != null) ckbAxises.SelectedIndexes = selectedIndex.ToList();

                cmbPoints.Clear();
                var list = PointsMgr.Ins.GetPoints(_station.Name);
                list.ForEach(item => cmbPoints.Items.Add(item));

                //VarInfo varInfo = cmbPoints.SelectedItem as VarInfo;
                //if (varInfo == null) return;
                MethodParms _methodParms = _actionItem.Parms[1];

                // VarInfo varInfo =GlobalVars.Ins.GetVar(_methodParms.VarGuid).Value;

                //_methodParms.VarName = cmbPoints.Text;
                //_methodParms.VarGuid = varInfo.VarId;
                //_methodParms.Value = GlobalVars.Ins.GetVar(_methodParms.VarGuid).Value;

                if (_methodParms != null)
                {
                    int index = list.FindIndex(item => item.Name == _methodParms.VarName);
                    if (index >= 0)
                    {
                        cmbPoints.SelectedIndex = index;
                    }
                }
            }

            cmbPoints.DisplayMember = "Name";

            #endregion 初始化底部控件

            LoadValue();
        }

        private void RefreshGridData()
        {
        }

        private void SetGrid()
        {
            grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            grid.RowHeadersVisible = false;
            grid.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            grid.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            grid.AllowUserToResizeRows = false;
            grid.MultiSelect = false;
            grid.AllowUserToAddRows = false;
            grid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            DataGridViewColumn col = new DataGridViewColumn();
            col.HeaderText = "点名";
            col.CellTemplate = new DataGridViewTextBoxCell();
            grid.Columns.Add(col);

            if (_station != null)
                foreach (var axis in _station.Axises)
                {
                    grid.Columns.Add(new DataGridViewColumn()
                    { HeaderText = axis.AxisName, CellTemplate = new DataGridViewTextBoxCell() });
                }
        }

        private void comObj_NodeSelected(object sender, TreeNode node)
        {
            _actionItem.ObjName = node.Text;
            _actionItem.ObjGuid = node.Tag.ToString();
            _station = GlobalVars.Ins.GetVar(_actionItem.ObjGuid).Value;
            ckbAxises.Items.Clear();
            foreach (var ax in _station.Axises)
            {
                ckbAxises.Items.Add(ax.AxisName);
            }
        }

        private void cmbReturn_NodeSelected(object sender, TreeNode node)
        {
            _actionItem.ReturnObjName = node.Text;
            _actionItem.ReturnObjGuid = node.Tag.ToString();
        }

        private void ckbAxises_ValueChanged(object sender, int index, string text, bool isChecked)
        {
            var axisEnabled = _actionItem.Parms[0];
            List<int> axisInUse = new List<int>();
            for (var i = 0; i < ckbAxises.SelectedIndexes.Count; i++)
            {
                axisInUse.Add(ckbAxises.SelectedIndexes[i]);
            }

            axisEnabled.Value = axisInUse.ToArray();
        }

        private void ckbInterpolation_CheckedChanged(object sender, EventArgs e)
        {
            _actionItem.Parms[4].Value = ckbInterpolation.Checked;
        }

        private void ckbRelMove_CheckedChanged(object sender, EventArgs e)
        {
            _actionItem.Parms[3].Value = ckbRelMove.Checked;
        }

        private void LoadValue()
        {
            ckbRelMove.Checked = _relMove;
            ckbInterpolation.Checked = _interpolation;
            intOverTime.Value = _overTime;
        }

        private void SaveValue()
        {
        }

        private void intOverTime_ValueChanged(object sender, int value)
        {
            _actionItem.Parms[5].Value = intOverTime.Value;
        }

        private void cmbPoints_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (!_bindingList[index].InputOrSelect)
            //{
            VarInfo varInfo = cmbPoints.SelectedItem as VarInfo;
            if (varInfo == null) return;
            MethodParms _methodParms = _actionItem.Parms[1];
            _methodParms.VarName = cmbPoints.Text;
            _methodParms.VarGuid = varInfo.VarId;
            _methodParms.Value = GlobalVars.Ins.GetVar(_methodParms.VarGuid).Value;

            double[] points = (double[])_methodParms.Value;
            if (points != null)
            {
                grid.Rows.Clear();
                List<object> rowData = new List<object> { varInfo.Name };
                foreach (var point in points)
                {
                    rowData.Add(point);
                }

                grid.Rows.Add(rowData.ToArray());
            }

            //FrmSelectVar dialog = new FrmSelectVar(_bindingList[index]);
            //    dialog.TopMost = true;
            //    dialog.BringToFront();
            //    dialog.Show();
            //}
            //else
            //{
            //    var valueType = _bindingList[index].Type;
            //retry:
            //    //手动输入的临时变量
            //    if (valueType == typeof(int).FullName)
            //    {
            //        int result = 0;
            //        if (UIInputDialog.InputIntegerDialog(ref result))
            //        {
            //            _bindingList[index].Value = result;
            //        }
            //    }
            //    if (valueType == typeof(uint).FullName)
            //    {
            //        int result = 0;
            //        if (UIInputDialog.InputIntegerDialog(ref result))
            //        {
            //            _bindingList[index].Value = (uint)result;
            //        }
            //    }
            //    if (valueType == typeof(short).FullName)
            //    {
            //        int result = 0;
            //        if (UIInputDialog.InputIntegerDialog(ref result))
            //        {
            //            _bindingList[index].Value = (short)result;
            //        }
            //    }
            //    if (valueType == typeof(ushort).FullName)
            //    {
            //        int result = 0;
            //        if (UIInputDialog.InputIntegerDialog(ref result))
            //        {
            //            _bindingList[index].Value = (ushort)result;
            //        }
            //    }
            //    if (valueType == typeof(long).FullName)
            //    {
            //        int result = 0;
            //        if (UIInputDialog.InputIntegerDialog(ref result))
            //        {
            //            _bindingList[index].Value = (long)result;
            //        }
            //    }
            //    if (valueType == typeof(ulong).FullName)
            //    {
            //        int result = 0;
            //        if (UIInputDialog.InputIntegerDialog(ref result))
            //        {
            //            _bindingList[index].Value = (long)result;
            //        }
            //    }

            //    if (valueType == typeof(float).FullName)
            //    {
            //        double result = 0;
            //        if (UIInputDialog.InputDoubleDialog(ref result))
            //        {
            //            _bindingList[index].Value = (float)result;
            //        }
            //    }
            //    if (valueType == typeof(double).FullName)
            //    {
            //        double result = 0;
            //        if (UIInputDialog.InputDoubleDialog(ref result))
            //        {
            //            _bindingList[index].Value = result;
            //        }
            //    }

            //    if (valueType == typeof(string).FullName)
            //    {
            //        string result = string.Empty;
            //        if (UIInputDialog.InputStringDialog(ref result))
            //        {
            //            _bindingList[index].Value = result;
            //        }
            //    }
            //    if (valueType == typeof(bool).FullName)
            //    {
            //        List<bool> listBool = new List<bool>() { true, false };
            //        int result = 0;
            //        if (this.ShowSelectDialog(ref result, listBool))
            //        {
            //            _bindingList[index].Value = listBool[result];
            //        }
            //    }
            //    if (valueType == typeof(int[]).FullName)
            //    {
            //        string result = string.Empty;
            //        if (UIInputDialog.InputStringDialog(ref result, true, "请输入整数数组，用逗号分割"))
            //        {
            //            var splitString = result.Split(',');
            //            List<int> list = new List<int>();
            //            foreach (var str in splitString)
            //            {
            //                if (int.TryParse(str, out int intValue))
            //                {
            //                    list.Add(intValue);
            //                }
            //                else
            //                {
            //                    UIMessageBox.ShowError("输入了错误的内容");
            //                    goto retry;
            //                }
            //            }

            //            JArray array = new JArray(list);
            //            _bindingList[index].Value = array;
            //        }
            //    }

            //    if (valueType == typeof(double[]).FullName)
            //    {
            //        string result = string.Empty;
            //        if (UIInputDialog.InputStringDialog(ref result, true, "请输入double数组，用逗号分割"))
            //        {
            //            var splitString = result.Split(',');
            //            List<double> list = new List<double>();
            //            foreach (var str in splitString)
            //            {
            //                if (double.TryParse(str, out double intValue))
            //                {
            //                    list.Add(intValue);
            //                }
            //                else
            //                {
            //                    UIMessageBox.ShowError("输入了错误的内容");
            //                    goto retry;
            //                }
            //            }

            //            JArray array = new JArray(list);
            //            _bindingList[index].Value = array;
            //        }
            //    }

            //    if (valueType == typeof(float[]).FullName)
            //    {
            //        string result = string.Empty;
            //        if (UIInputDialog.InputStringDialog(ref result, true, "请输入浮点数数组，用逗号分割"))
            //        {
            //            var splitString = result.Split(',');
            //            List<float> list = new List<float>();
            //            foreach (var str in splitString)
            //            {
            //                if (float.TryParse(str, out float intValue))
            //                {
            //                    list.Add(intValue);
            //                }
            //                else
            //                {
            //                    UIMessageBox.ShowError("输入了错误的内容");
            //                    goto retry;
            //                }
            //            }

            //            JArray array = new JArray(list);
            //            _bindingList[index].Value = array;
            //        }
            //    }

            //}
        }
    }
}